import {
    AsyncStorage,
    Alert
} from "react-native"
import moment from 'moment'

// const ip = "http://192.168.1.4:7000/"
const ip = "http://yuncommunity.com:7000/"
const host = ip + "v1/client/"

export function request(api, params, success, fail) {
    AsyncStorage.getItem("Token", (res, token) => {
        params.Token = token
        let url = host + api + "?"
        for (let key in params) {
            url += key + "=" + params[key] + "&"
        }
        console.log("fetch ", url)
        fetch(url)
            .then(resp => resp.json())
            .then(res => {
                if (res.code < 0) {
                    Alert.alert(res.data)
                    AsyncStorage.setItem("Token", "")
                    AsyncStorage.setItem("UserInfo", "")
                } if (res.code === 0) {
                    if (success) {
                        success(res.data)
                    }
                } else {
                    if (fail) {
                        fail(res.data, res.code)
                    }
                }
            })
            .catch(e => console.log(e))
    })
}

export function formatTime(time) {
    if (!time) {
        return ""
    }
    if (time.length < 16) {
        return time
    }
    return moment(time).format("YYYY-MM-DD HH:mm")
}

export function getUrl(api) {
    return host + api
}

export function addZero(num) {
    num = parseInt(num)
    if (num < 10) {
        return "0" + num
    }
    return num
}

export function formatMinute(minute) {
    return addZero(minute / 60) + ":" + addZero(minute % 60)
}

export function randomColor(i) {
    // return `rgb(${Math.floor(Math.random() * 255)}, ${i * 5}, ${132})`
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}